// Variables whose values will be later be loaded from database

var totalTurns 	= 	6;
var currentTurn = 	0;
var loadedtext 	=	"This is the story!";
var wholestory	= 	" ";


// Global variables
var GAME_MODE_UNKNOWN = -1,
    GAME_MODE_WRITING = 0,
    GAME_MODE_DRAWING = 1,
    GAME_MODE_COMPLETE = 2;
    
var WINDOW_HEIGHT_SCALAR = 0.5;
    
var gameMode = GAME_MODE_UNKNOWN;

var drawingBox = null;	//the div box that contains the canvas
var canvas = null;	//the actual canvas object
var tool;		//the canvas drawing tool
var brush;		//the canvas drawing brush
var context;		//the canvas drawing context
var story;          	//story text area
 
var dataURL; 
 
//setup the drawing canvas
function initDrawingCanvas()
{
    // "Done" Button used to switch between drawing and writing
    var doneButton = $("#finishedButton");
    
    // Story Text Area
    story = $("#storyTextArea");
    
    
    // Canvas element
    canvas = $("#drawingCanvas")[0];//the [0] is needed to get the canvas element, instead of the jquery object
    
    //=============Setup the Canvas Element=================
    
    // Get the 2D canvas context
    context = canvas.getContext('2d');
    
    // look for errors with canvas
    if (!canvas)
    {
        alert('Error 1: This game is not supported in your browser.');
        return;
    }
    
    if (!canvas.getContext)
    {
        alert('Error 2: This game is not supported in your browser.');
        return;
    }
    
    if (!context)
    {
        alert('Error 3: This game is not supported in your browser.');
        return;
    }


    drawingBox = $("#DrawingBox");
    
    //set the initial size of the drawing canvas
    resizeDrawingCanvas();

    // Pencil tool instance.
    //tool = new tool_pencil();
    
    //setup the done button's click event listener
    doneButton.bind('click', finished_turn);
    
    // initialize drawing or writing turn
    load_turn();
}

//resizes the drawing canvas to match it's container's size
function resizeDrawingCanvas()
{
    if(canvas != null && drawingBox != null)
    {
	bottom_box = document.getElementById("LeftColumn");
	
	//Set the canvas width and height
	canvas.width = bottom_box.clientWidth;//drawingBox.width();
	canvas.height = window.innerHeight * WINDOW_HEIGHT_SCALAR;//drawingBox.height();
    }
}


// This painting tool works like a drawing pencil which tracks the mouse movements.
function tool_pencil ()
{
    var tool = this;
    this.started = false;

    // Mouse Down - Begin line
    this.mousedown = function (ev)
    {
        context.beginPath();
        context.moveTo(ev._x, ev._y);
        tool.started = true;
    };

    // Mouse Move - Draw line
    this.mousemove = function (ev)
    {
	if (tool.started)
	{
	    context.lineTo(ev._x, ev._y);
	    context.stroke();
	}
    };

    // Mouse Release - End line
    this.mouseup = function (ev)
    {
	if (tool.started)
	{
	    tool.mousemove(ev);
	    tool.started = false;
	}
    };
}


// The general-purpose event handler.
// determines the mouse position relative to the canvas element.
function ev_canvas (ev) 
{
    if (ev.layerX || ev.layerX == 0)		// Firefox
    { 			
	ev._x = ev.layerX;
	ev._y = ev.layerY;
    }
    else if (ev.offsetX || ev.offsetX == 0)	// Opera
    { 
	ev._x = ev.offsetX;
	ev._y = ev.offsetY;
    }

    // Call the event handler of the tool.
    var func = tool[ev.type];
    
    if (func)
    {
	func(ev);
    }
}

function load_turn()
{
    // Determine current state of game (drawing, writing, or done)
    if (currentTurn >= totalTurns)
    {
	gameMode = GAME_MODE_COMPLETE; // Game Over!
    }
    else
    {
	gameMode = currentTurn % 2;	// Game Active!
    }

	
    // Load Correct game state - Drawing, Writing, or whatever
    // Lock unused features
    switch (gameMode) 
    {
	//Writing Mode Turn
	case GAME_MODE_WRITING:
	    story.disabled=false;		    // Enable writing area
	    story.enabled = "enabled";		    // Don't lock text in place
	    
	    // Prevent drawing by removing event listeners
	    
	    canvas.removeEventListener('mousedown', onCanvasMouseDown, false);
	    
	    /*
	    canvas.removeEventListener('mousemove', ev_canvas, false);
	    canvas.removeEventListener('mouseup',   ev_canvas, false);
	    */
	    
	    
	    //select all the story text when first entered
	    SelectAll();
	    
	    break;
	
	//Drawing Mode Turn
	case GAME_MODE_DRAWING:
	    story.value = loadedtext;		// Display loaded text
	    story.disabled = "disabled";	// Lock text in place

	    //canvas.width = canvas.width;		// clear canvas
	    canvas.style.backgroundColor = "white";
	    
	    
	    // Add mouse event listeners for canvas drawing
	    canvas.addEventListener('mousedown', onCanvasMouseDown, false);
	    
	    /*
	    canvas.addEventListener('mousemove', ev_canvas, false);
	    canvas.addEventListener('mouseup',   ev_canvas, false);
	    */

	    break;
		
	//Game is Over
	case GAME_MODE_COMPLETE:
	    // Prevent drawing by removing event listeners
	    
	    canvas.removeEventListener('mousedown', onCanvasMouseDown, false);
	    
	    /*
	    canvas.removeEventListener('mousemove', ev_canvas, false);
	    canvas.removeEventListener('mouseup',   ev_canvas, false);
	    */
	
	    // Show whole story for debugging
	    story.value = wholestory;
	    
	    break;
		
	default:
	    break;
		
    }
}


// ** Finished Turn  **
// Write info back to database
// init next turn
function finished_turn (ev)
{
    //increment the number of turns
    currentTurn++;

    switch (gameMode)
    {
	// Writing Mode Turn
	case GAME_MODE_WRITING:
	    
	    // concat text to story with text between them used for parsing
	    wholestory = wholestory.concat( "%Entry", currentTurn, "%", story.value);

	    // Save text
	    
	    break;
		
	// Drawing Mode Turn
	case GAME_MODE_DRAWING:
		// Save Drawing
		dataURL = canvas.toDataURL();
		break;
		
	// Game is Over
	case GAME_MODE_COMPLETE:
		//story = wholestory;
		break;
		
    }
    
    // Delay until next turn -> wait until other are ready
    
    // Load next drawing or writing turn
    load_turn();
}

// select all the text in the story box
function SelectAll()
{
    story.focus();
    story.select();
}